import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path:'/index',
    component:()=>import('../pages/index.vue'),
    children:[
      {
        path:'/home',
        component:()=>import('../views/home.vue')
      },
      {
        path:'/menu',
        component:()=>import('../views/menu/menu.vue')
      },
      {
        path:'/role',
        component:()=>import('../views/role/index.vue')
      },
      {
        path:'/user',
        component:()=>import('../views/user/index.vue')
      },
      {
        path:'/category',
        component:()=>import('../views/cate/index.vue'),
        meta: {title: '商品分类'}
      },
      {
        path:'/specs',
        component:()=>import('../views/specs/index.vue'),
        meta: {title: '商品规格'}
      },
      {
        path:'/goods',
        component:()=>import('../views/goods/index.vue'),
        meta: {title: '商品管理'}
      },
      {
        path:'',
        redirect:'/home'
      }
    ]
  },
  {
    path:'/login',
    component:()=>import('../pages/login.vue')
  },
  {
    path:'*',
    redirect:'/index'
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫：未登录时可以看的页面：/login和/home，其他的需要登录
router.beforeEach((to, from, next) => {
  document.title = to.meta.title || '后台管理';
  const isLogin = localStorage.getItem('userInfo');
  if(isLogin) {
    // 登录过后，不拦截
    next();
  }else {
    // 没有登录，只能看/login和/home
    if(to.path === '/login' || to.path === '/home') {
      next();
    }else {
      next('/login');
    }
  }
})

export default router
